package com.bidu.web.interceptor;

import com.alibaba.fastjson.JSON;
//import com.integral.commission.common.utils.ThreadTokenHelper;
import com.bidu.common.ThreadTokenHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

public class RequestLoggerHandler extends HandlerInterceptorAdapter {

    private static Logger logger = LoggerFactory.getLogger(RequestLoggerHandler.class);

    private ThreadLocal<Long> startTime = new ThreadLocal();

    public RequestLoggerHandler() {
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        this.startTime.set(Long.valueOf(System.currentTimeMillis()));
        MDC.put("traceId", UUID.randomUUID().toString().replaceAll("-", "").substring(16));
        logger.info("[http]preHandle url: {}, inParams: {}", new Object[]{request.getRequestURL(), this.toJSONString(request.getParameterMap())});
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        logger.info("[http]postHandle url: {}, cause [{}] ms", new Object[]{request.getRequestURL(), Long.valueOf(System.currentTimeMillis() - ((Long) this.startTime.get()).longValue())});
        ThreadTokenHelper.clear();
        //        this.startTime.remove();
    }

    private String toJSONString(Object object) {
        try {
            return JSON.toJSONString(object);
        } catch (Exception var3) {
            logger.warn("request请求参数序列化{}异常......");
            var3.printStackTrace();
            return null;
        }
    }
}
